#!/usr/bin/perl
use CGI qw ( :standard );
use Encode;
use File::Copy;

my $wordscount;

sub form_html()
    {
    print h3 ('CSV contacts converter');

    print filefield (
		    -name=>'source_filename',
		    -size=>50);
    }

print header;
print start_html ( -title=>'CSV Contacts Converter');
print p;

print start_form(-enctype=>&CGI::MULTIPART);

form_html();

print p;

print "Note for separators: Nokia, Blackberry and Outlook use comma(,) while Iphone uses semicolon(;)";

print "<table border=1 >";
print "<th width=100>Separator:</th>";
print "<th width=200>Source:</th>";


print "<tr>";
print "<td>";



print radio_group(
	    -name=>'separator',
	    -values=>[',',';'],
	    -default=>',',
	    -rows=>2,
	    -cols=>1,
	    );
	    
print "</td>";	    
print "<td>";



print radio_group(
	    -name=>'source',
	    -values=>['nokia','iphone','outlook','blackberry'],
	    -default=>'nokia',
	    -rows=>2,
	    -cols=>2,
	    );

print "</td>";	    
print "</tr>";
print "</table>";
	    
print p;

print submit(
	    -name=>'submit',
	    -value=>'submit');



print end_form;

$filename = param('source_filename');
$filename =~ s/^.*\\//;

$CGI::POST_MAX = 1024 * 5000;

# file upload
my $q=new CGI;
uploadfile($q->param('source_filename'),$filename);

#file upload
sub uploadfile($)
    {
    my ($filehandle,$filename)=@_;
    my $outputfile='/tmp/'.$filename;
    my ($bytesread,$buffer);
    my $numbytes=1024;
	
    open (OUTFILE,">","$outputfile");
    while ($bytesread=read($filehandle,$buffer,$numbytes))
        {
        print OUTFILE $buffer;
        }
    close OUTFILE;
        
    }

					    									    
sub convert()
{
    if (param)
    {
    $inputfile='/tmp/'.$filename;

# setting output filename
    $outputfile = $inputfile;
    $outputfile =~ s/.csv/.vcf/i;
    if ($outputfile eq $inputfile)
	{
        $outputfile=$outputfile.".vcf";
        }
            
#incremeting value
    $i = 66400000000;
    
#current date calculation and transform
    ($cur_sec,$cur_min,$cur_hour,$cur_mday,$cur_mon,$cur_year,$cur_wday,$cur_yday,$cur_isdst) = localtime(time);
    $cur_year = sprintf("%02d", $cur_year % 100);

    $cur_mon=$cur_mon+1;
    if ($cur_mday<10) {$cur_mday="0".$cur_mday};
    if ($cur_mon<10) {$cur_mon="0".$cur_mon};
    if ($cur_hour<10) {$cur_hour="0".$cur_hour};
    if ($cur_min<10) {$cur_min="0".$cur_min};
    if ($cur_sec<10) {$cur_hour="0".$cur_sec};

    $cur_year="20".$cur_year;
    $cur_date=$cur_mday.".".$cur_mon.".".$cur_year;
                  
    $vcarddate="REV:".$cur_year."-".$cur_mon."-".$cur_mday."T".$cur_hour.":".$cur_min.":".$cur_sec."Z";

    if (param("source") eq "nokia")
	{
    open (FH, "<:raw:encoding(UTF-16)", $inputfile) or die "Cannot open $inputfile for reading!\n";
    open (FHOUT, ">$outputfile" ) or die "Cannot write $outputfile for reading!\n";
        
    @inputfilelines=<FH>;
	foreach (@inputfilelines)
	    {

	    # debug
	    #	print $_;
	    $separator = param("separator");
	    
	    @contactsarray = split($separator,$_);
	    
# importing name, company, e-mail
	    $vcardstring = "BEGIN:VCARD\nVERSION:3.0\nUID:pas-id-519B0".$i."\nN:".@contactsarray[1]." ".@contactsarray[3]."\nORG:".@contactsarray[6]."EMAIL;TYPE=INTERNET:".@contactsarray[15]."\n";

# importing various phone numbers
	if (@contactsarray[12] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=CELL:".@contactsarray[13]."\n";
	    }
	if (@contactsarray[13] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=HOME:".@contactsarray[14]."\n";
	    }
	if (@contactsarray[27] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=WORK:".@contactsarray[27]."\n";
	    }
	if (@contactsarray[28] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=FAX:".@contactsarray[28]."\n";
	    }

# closing record
    $vcardstring = $vcardstring.$vcarddate."\nEND:VCARD\n\n";



# removing double quotes
	$vcardstring =~ s/\"//g;

# incrementing
	$i=$i+1;

# writing outputfile
	print FHOUT $vcardstring;
	
	
	}

    close FH;
    close FHOUT;

	}

    elsif (param("source") eq "outlook")
	{


    open (FH, "<:raw:encoding(CP866)", $inputfile) or die "Cannot open $inputfile for reading!\n";
    open (FHOUT, ">$outputfile" ) or die "Cannot write $outputfile for reading!\n";
        
    @inputfilelines=<FH>;
	foreach (@inputfilelines)
	    {

	    # debug
	    #	print $_;
	    $separator = param("separator");
# get rid of unprintable non-ASCII characters

	    
	    @contactsarray = split($separator,$_);

#	    if (@contactsarray[1] ne '""' or @contactsarray[3] ne '""')
	    if (@contactsarray[1] ne '' or @contactsarray[3] ne '')
	    {
# importing name, company, e-mail

	    $vcardstring = "BEGIN:VCARD\nVERSION:3.0\nUID:pas-id-519B0".$i."\nN:".@contactsarray[1]." ".@contactsarray[3]."\nORG:".@contactsarray[6]."EMAIL;TYPE=INTERNET:".@contactsarray[15]."\n";

# importing various phone numbers
	if (@contactsarray[37] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=CELL:".@contactsarray[37]."\n";
	    }
	if (@contactsarray[38] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=HOME:".@contactsarray[38]."\n";
	    }
	if (@contactsarray[39] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=WORK:".@contactsarray[39]."\n";
	    }
	if (@contactsarray[40] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=FAX:".@contactsarray[40]."\n";
	    }

# closing record
    $vcardstring = $vcardstring.$vcarddate."\nEND:VCARD\n\n";



# removing double quotes
	$vcardstring =~ s/\"//g;

# incrementing
	$i=$i+1;

# writing outputfile
	print FHOUT $vcardstring;
	    }	
	
	}

    close FH;
    close FHOUT;

	
	}

 elsif (param("source") eq "blackberry")
	{


    open (FH, "<:raw:encoding(CP1251)", $inputfile) or die "Cannot open $inputfile for reading!\n";
    open (FHOUT, ">$outputfile" ) or die "Cannot write $outputfile for reading!\n";
        
    @inputfilelines=<FH>;
	foreach (@inputfilelines)
	    {


	    # debug


	    #	print $_;
	    $separator = param("separator");
	    
	    @contactsarray = split($separator,$_);

#	    if (@contactsarray[1] ne '""' or @contactsarray[3] ne '""')
	    if (@contactsarray[0] ne '' or @contactsarray[1] ne ''  or @contactsarray[2] ne '')
	    {
# importing name, company, e-mail

	    $vcardstring = "BEGIN:VCARD\nVERSION:3.0\nUID:pas-id-519B0".$i."\nN:".@contactsarray[0]." ".@contactsarray[1]." ".@contactsarray[2]."\nORG:".@contactsarray[4]."EMAIL;TYPE=INTERNET:".@contactsarray[13]."\n";

# importing various phone numbers
	if (@contactsarray[9] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=CELL:".@contactsarray[9]."\n";
	    }
	if (@contactsarray[10] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=HOME:".@contactsarray[10]."\n";
	    }
	if (@contactsarray[11] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=WORK:".@contactsarray[11]."\n";
	    }
	if (@contactsarray[12] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=FAX:".@contactsarray[12]."\n";
	    }

# closing record
    $vcardstring = $vcardstring.$vcarddate."\nEND:VCARD\n\n";



# removing double quotes
	$vcardstring =~ s/\"//g;

# incrementing
	$i=$i+1;

# writing outputfile - with error handling
        print FHOUT $vcardstring;
	    }	
	
	}

    close FH;
    close FHOUT;

	
	}


 elsif (param("source") eq "iphone")
	{


    open (FH, "<:raw:encoding(CP1251)", $inputfile) or die "Cannot open $inputfile for reading!\n";
    open (FHOUT, ">$outputfile" ) or die "Cannot write $outputfile for reading!\n";
        
    @inputfilelines=<FH>;
	foreach (@inputfilelines)
	    {


	    # debug


	    #	print $_;
	    $separator = param("separator");
	    
	    @contactsarray = split($separator,$_);

#	    if (@contactsarray[1] ne '""' or @contactsarray[3] ne '""')
	    if (@contactsarray[0] ne '' or @contactsarray[1] ne ''  or @contactsarray[2] ne '')
	    {
# importing name, company, e-mail

	    $vcardstring = "BEGIN:VCARD\nVERSION:3.0\nUID:pas-id-519B0".$i."\nN:".@contactsarray[0]." ".@contactsarray[1]." ".@contactsarray[2]."\nORG:".@contactsarray[25]."EMAIL;TYPE=INTERNET:".@contactsarray[5]."\n";

# importing various phone numbers
	if (@contactsarray[11] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=CELL:".@contactsarray[11]."\n";
	    }
	if (@contactsarray[12] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=HOME:".@contactsarray[12]."\n";
	    }
	if (@contactsarray[13] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=WORK:".@contactsarray[13]."\n";
	    }
	if (@contactsarray[14] ne "")
	    {
	    $vcardstring=$vcardstring."TEL;TYPE=FAX:".@contactsarray[14]."\n";
	    }

# closing record
    $vcardstring = $vcardstring.$vcarddate."\nEND:VCARD\n\n";



# removing double quotes
	$vcardstring =~ s/\"//g;

# incrementing
	$i=$i+1;

# writing outputfile - with error handling
        print FHOUT $vcardstring;
	    }	
	
	}

    close FH;
    close FHOUT;

	
	}


    else 
	{
# debug	
	print "Convertor not  yet ready for ".param("source");
	}


    $linkfilename = $outputfile;
    $linkfilename =~ s/\/tmp\///;

    $dstpath = "/var/www/html/vcf/".$linkfilename;

    # deleting file for security reasons
    unlink ('/tmp/'.$filename);
    
#    print $dstpath;    
    copy ($outputfile,$dstpath) or die "Copy failed: $!";
    

    $filelink = 'top.location.href="/vcf/'.$linkfilename.'"';
    
    print button(
		-name=>'download',
		-value=>'download',
		-onClick=> $filelink,
		);
    
# debug
#    print $vcardstring;
    print p;


    
    }
else 
    {
    print "\nNo File Defined\n";
    }
}

print h4 ('Result:');

if (param('submit'))
    {
    convert();
    }


print end_html;


